
#DUMMYCONNECTION: 
#from DummyConnection import ibConnection, message
from ib.opt import ibConnection, message
   
from MarketDepthItem import MarketDepthItem
from Tick import Tick

from threading import Thread
import logging

class Producer(Thread):
    
    def __init__(self, contracts, queue, connectparams): 
        super(Producer, self).__init__()
        self.contracts  = contracts        
        self.queue      = queue
        self.connected  = False
        
        self.ibconn     = ibConnection(port=int(connectparams['port']))
        self.ibconn.register(self.storeTick,     message.TickPrice)
        self.ibconn.register(self.storeMktDepth, message.UpdateMktDepth)
                  
        self.connected = self.ibconn.connect() 

    def storeTick(self, msg):           
        logging.getLogger().debug("Message received %s", msg)
        self.queue.put(Tick(msg))
        
    def storeMktDepth(self, msg) :    
        logging.getLogger().debug("Mkt depth message received %s", msg)
        self.queue.put(MarketDepthItem(msg))               

    def run(self):
        logging.getLogger().debug("Connecting to IBGateway")                
        if self.connected == False:
            logging.getLogger().fatal("ERROR:Unable to connect to IB Gateway") 
        else:
            logging.getLogger().debug("Starting producer thread")            
            self.registerMktData()        

    def registerMktData(self):
        logging.getLogger().debug("Registering market data")
        for i in range(len(self.contracts)):
            logging.getLogger().debug("Registering %s" % self.contracts[i].m_symbol)
            self.ibconn.reqMktData (i, self.contracts[i], '', False)
            self.ibconn.reqMktDepth(i, self.contracts[i], 3)
        
    def stop(self):
        logging.getLogger().debug("Stopping producer thread")
        self.cancelMktData() 
        self.queue.put(None)
        self.ibconn.disconnect()
        self.connected = False

    def cancelMktData(self):          
        logging.getLogger().debug("Cancelling market data")
        for i in range(len(self.contracts)):
            self.ibconn.cancelMktData(i)           
            self.ibconn.cancelMktDepth(i)
            
    def __del__(self):           
        self.stop()
        self.ibconn.disconnect()
        self.connected = False
